package alibaba.testutils;

import java.io.File;

import alibaba.server.AlibabaServer;

public class ServerTestUtils {

    public static class ServerRunner implements Runnable {
        
        private static final int SERVER_POLLING_INTERVAL = 1000; // ms
        private String backupDirPath;
        private boolean cleanup = false;
        private boolean shutDown = false;
        private Thread thread;
        
        public ServerRunner(String backupDirPath, boolean cleanup) {
            this.cleanup = cleanup;
            this.backupDirPath = backupDirPath;
        }
        
        public synchronized void shutdownServer() {
            shutDown = true;
            try {
                thread.join();
            } catch (InterruptedException e) {
                System.out.println("Interrupted while waiting for server to end");
            }
        }
        
        private void setThread(Thread t) {
            this.thread = t;
        }
        
        // don't call this when server is runnning
        public synchronized void cleanup() {
            for (File file : new File(backupDirPath).listFiles()) {
                file.delete();
            }
        }
        
        public void run() {
            
            if (cleanup) {
                cleanup();
            }
            
            Thread serverThread = new Thread(new Runnable() {
                public void run() {
                    AlibabaServer.main(new String[] { backupDirPath });
                }
            });
            
            serverThread.start();
            
            while(!shutDown) {
                try {
                    Thread.sleep(SERVER_POLLING_INTERVAL);
                } catch (InterruptedException e) {
                    System.err.println("Server Interrupted");
                }
            }
            
            serverThread.interrupt(); // end server's main thread
            
        }
    }
    
    public static ServerRunner startServer(String backupDirPath, boolean cleanup) {
        ServerRunner runner = new ServerRunner(backupDirPath, cleanup);
        Thread serverThread = new Thread(runner);
        runner.setThread(serverThread);
        serverThread.start();
        return runner;
    }
        
}
